package rs;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import rs.util.Log;
import rs.util.StringUtil;

public class Extractor {

	/**
	 * 解析文档. 通过指定URL的document和给定的rules,解析生成对应的model
	 * @param doc
	 * @param rules
	 * @param model
	 */
	public void work(Document doc, Map<String, String> rules, Map<String, Object> model){
		Log.debug("Extracting: " + doc.baseUri());
		for(Entry<String, String> ruleEntry : rules.entrySet()){
			String key = ruleEntry.getKey();
			String rule = ruleEntry.getValue();
			Object ruleResult;
			String docHtml = null;
			boolean multiple = false;
			if(rule.startsWith(Conf.MULTI_SIGN)){
				multiple = true;
				rule = rule.substring(Conf.MULTI_SIGN.length());
			}
			if(rule.startsWith(Conf.REGEXP_SIGN)){
				//按照正则方式抽取.
				if(docHtml == null){
					docHtml = doc.html();
				}
				if(multiple){
					ruleResult = StringUtil.findAll(docHtml, rule.substring(Conf.REGEXP_SIGN.length()));
				} else {
					ruleResult = StringUtil.find(docHtml, rule.substring(Conf.REGEXP_SIGN.length()), "");
				}
			} else {
				//按照xpath方式抽取
				String[] ruleAttr = rule.split(Conf.ATTR_SIGN);
				ruleResult = extractByDom(doc, ruleAttr, multiple);
			}
			Log.debug("Find: " + key +" - "+ ruleResult);
			model.put(key, ruleResult);
		}
	}

	private Object extractByDom(Document doc, String[] ruleAttr, boolean multiple) {
		Object ruleResult;
		if(multiple){
			Elements elements = doc.select(ruleAttr[0]);
			List<String> everyResult = new ArrayList<String>();
			for(Element el : elements){
				if(ruleAttr.length == 2){//选取属性
					everyResult.add(el.attr(ruleAttr[1]));
				} else {//选取innerHTML
					everyResult.add(el.html());
				}
			}
			ruleResult = everyResult.toArray(new String[everyResult.size()]);
		} else {
			if(ruleAttr.length == 2){//选取属性
				ruleResult = doc.select(ruleAttr[0]).first().attr(ruleAttr[1]);
			} else {//选取innerHTML
				ruleResult = doc.select(ruleAttr[0]).first().html();
			}
		}
		return ruleResult;
	}
	
	
	public static void main(String[] args) {
		String s = ".primary.cf>h1>a#AT";
		String[] r = s.split("#ATTR#");
		System.out.println(r.length + " " + r[0] );
		System.out.println(Double.parseDouble("&yen; 98"));
	}
}
